<!-- 产线状态登记 -->
<template>
  <basic-container class="production-page">
    <avue-crud
      :option="option"
      :table-loading="loading"
      :defaults.sync="defaults"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" icon="el-icon-plus" size="small" v-if="permission.machineType_add" @click="handleAdd">新 增</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" v-if="permission.machineType_add" @click="rowView(row)">详情</el-button>
        <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.machineType_edit" @click="rowUpdate(row)">编辑</el-button>
        <el-button icon="el-icon-delete" size="small" type="text" v-if="permission.machineType_delete" @click="rowDel(row)">删除</el-button>
        <el-button
          icon="el-icon-circle-check"
          size="small"
          type="text"
          v-if="!row.enabled && permission.machineType_enableOrDisable"
          @click.stop="handleEnableOrDisable(row, true)"
          v-preventReClick
          >启用
        </el-button>
        <el-button
          icon="el-icon-circle-close"
          size="small"
          type="text"
          v-if="row.enabled && permission.machineType_enableOrDisable"
          @click.stop="handleEnableOrDisable(row, false)"
          v-preventReClick
          >禁用
        </el-button>
      </template>
      <template slot-scope="{ row }" slot="enabled">
        <el-tag>{{ row.enabled ? '是' : '否' }}</el-tag>
      </template>
    </avue-crud>
    <el-dialog ref="dialog" v-if="showDialog" :title="dialogTitle" append-to-body :visible.sync="showDialog" :close-on-click-modal="false" top="5vh" @close="closeDialog">
      <avue-form ref="dialogProperties" v-model="form" :option="dialogOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle === '新增'" type="primary" size="small" @click="submit" v-preventReClick>
          <i class="el-icon-circle-plus-outline"></i><span>保 存</span>
        </el-button>
        <el-button v-if="dialogTitle === '编辑'" type="primary" size="small" @click="submit" v-preventReClick>
          <i class="el-icon-circle-check"></i><span>修 改</span>
        </el-button>
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <!-- 物料基础数据 弹框 -->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
  </basic-container>
</template>
<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getList, remove, getDetail, updatEnable, add } from '@/api/equipment-manage/machineType';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  name: '',
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'MACHINE_TYPE',
      dialogTitle: '新增',
      showDialog: false,
      changeData: {},
      defaults: {},
      form: {},
      query: {},
      loading: false,
      data: [],
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      specialTypeObj: {
        AGINGCAR: '老化车',
        MACHINE: '设备',
        PRINTER: '打印机'
      },
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      dialogOption: {
        submitBtn: false,
        emptyBtn: false,
        detail: false,
        group: [
          {
            label: '基本数据',
            arrow: false,
            prop: 'baseInfo',
            labelWidth: 100,
            display: true,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '类型编码',
                prop: 'code',
                disabled: false,
                rules: [
                  {
                    required: true,
                    message: '请输入类型编码'
                  }
                ]
              },
              {
                label: '类型名称',
                prop: 'name',
                disabled: false,
                rules: [
                  {
                    required: true,
                    message: '请输入类型名称'
                  }
                ]
              },
              {
                label: '描述',
                prop: 'remark',
                type: 'textarea',
                minRows: 3,
                maxRows: 3
              }
            ]
          },
          {
            label: '夹治具及辅料配置',
            arrow: false,
            prop: 'toolConfig',
            labelWidth: 100,
            display: true,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '需采集工具',
                prop: 'collectTool',
                type: 'checkbox',
                row: true,
                span: 24,
                dicData: [
                  {
                    label: '钢网',
                    value: 'STEELMESH'
                  },
                  {
                    label: '刮刀',
                    value: 'SCRAPER'
                  },
                  {
                    label: '飞达',
                    value: 'FEEDER'
                  },
                  {
                    label: '飞达车',
                    value: 'FEEDERBUS'
                  },
                  {
                    label: '刀具',
                    value: 'KNIFE'
                  },
                  {
                    label: '刀模',
                    value: 'KNIFE_MODE'
                  },
                  {
                    label: '网版',
                    value: 'MESH_PANELS'
                  }
                ]
              },
              {
                label: '需采集辅料',
                prop: 'collectMaterial',
                type: 'checkbox',
                row: true,
                dicData: [
                  {
                    label: '锡膏',
                    value: 'SOLDER'
                  },
                  {
                    label: '胶水',
                    value: 'GLUE'
                  }
                ]
              }
            ]
          }
        ]
      },
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 4,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        viewTitle: '详情',
        viewBtnText: '详情',
        addBtn: false,
        addTitle: '登记',
        editBtn: false,
        delBtn: false,
        selection: false,
        dialogClickModal: false,
        menu: true,
        menuWidth: 270,
        labelWidth: 130,
        columnBtn: false,
        column: [
          {
            label: '类型编码',
            prop: 'code',
            search: true
          },
          {
            label: '类型名称',
            prop: 'name',
            search: true
          },
          {
            label: '描述',
            prop: 'remark'
          },
          {
            label: '编订人',
            prop: 'createUserName'
          },
          {
            label: '编订日期',
            prop: 'createTime'
          },
          {
            label: '是否启用',
            prop: 'enabled',
            type: 'select',
            dicData: [
              {
                label: '是',
                value: true
              },
              {
                label: '否',
                value: false
              }
            ]
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.machineType_view, false),
        addBtn: this.vaildData(this.permission.machineType_add, false),
        editBtn: this.vaildData(this.permission.machineType_edit, false),
        delBtn: this.vaildData(this.permission.machineType_delete, false)
      };
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    submit() {
      this.$refs.dialogProperties.validate((valid, done) => {
        if (valid) {
          let params = this.form;

          if (Array.isArray(params.collectTool) && params.collectTool.length > 0) {
            let obj = {};
            params.collectTool.forEach((item, index) => {
              obj[item] = true;
            });
            params.collectTool = JSON.stringify(obj);
          } else {
            params.collectTool = JSON.stringify({});
          }

          if (Array.isArray(params.collectMaterial) && params.collectMaterial.length > 0) {
            let obj = {};
            params.collectMaterial.forEach((item, index) => {
              obj[item] = true;
            });
            params.collectMaterial = JSON.stringify(obj);
          } else {
            params.collectMaterial = JSON.stringify({});
          }

          add(params).then((res) => {
            this.showDialog = false;
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功！'
            });
          });
        }
        done();
      });
    },
    closeDialog() {
      this.$refs.dialogProperties.resetFields();
    },
    handleEnableOrDisable(row, enabled) {
      updatEnable({
        id: row.id,
        enabled
      }).then((res) => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: `${enabled ? '已启用!' : '已禁用!'}`
        });
      });
    },
    handleAdd() {
      this.dialogTitle = '新增';
      this.form = {};
      this.dialogOption.detail = false;
      this.showDialog = true;
    },
    rowView(row) {
      this.dialogTitle = '详情';
      this.dialogOption.detail = true;
      this.getDetailRequest(row.id);
      this.showDialog = true;
    },
    rowUpdate(row) {
      this.dialogTitle = '编辑';
      this.dialogOption.detail = false;
      this.getDetailRequest(row.id);
      this.showDialog = true;
    },
    isDisabledCodeAndName(boolean) {
      let code = this.findObject(this.dialogOption.group, 'code');
      let name = this.findObject(this.dialogOption.group, 'name');
      code.disabled = boolean;
      name.disabled = boolean;
    },
    getDetailRequest(id) {
      getDetail(id).then((res) => {
        let data = res.data.data;
        if (typeof data.collectTool === 'string') {
          let object = JSON.parse(data.collectTool);
          let arr = [];
          for (const key in object) {
            arr.push(key);
          }
          data.collectTool = arr;
        }
        if (typeof data.collectMaterial === 'string') {
          let object = JSON.parse(data.collectMaterial);
          let arr = [];
          for (const key in object) {
            arr.push(key);
          }
          data.collectMaterial = arr;
        }
        this.form = data;
        if (this.dialogTitle == '编辑' && this.specialTypeObj[data.code]) {
          this.isDisabledCodeAndName(true);
        } else {
          this.isDisabledCodeAndName(false);
        }
      });
    },
    rowDel(row) {
      if (this.specialTypeObj[row.code]) {
        this.$message({
          type: 'warning',
          message: '当前类别不能进行删除！'
        });
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records || [];
        this.loading = false;
      });
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>
<style lang="scss"></style>
